#include <iostream>
#include <string>
#include <vector>
#include <iconv.h>
#include <cerrno>
#include <cstring>

std::string convert_gbk_to_utf8(const char* input, int input_len) {
    // Initialize iconv conversion descriptor
    iconv_t cd = iconv_open("GB18030", "GBK");
    if (cd == (iconv_t)-1) {
        std::cerr << "Error initializing iconv: " << strerror(errno) << std::endl;
        return "";
    }

    // Determine the size of the output buffer
    size_t output_bytes_left = input_len * 4; // UTF-8 can take up to 4 bytes per character
    std::vector<char> output_buf(output_bytes_left);
    char* output_ptr = output_buf.data();
    size_t output_bytes_used = 0;

    // Prepare the input buffer
    char* input_ptr = const_cast<char*>(input);
    size_t input_bytes_left = input_len;

    // Perform the conversion
    size_t result = iconv(cd, &input_ptr, &input_bytes_left, &output_ptr, &output_bytes_left);
    if (result == (size_t)-1) {
        std::cerr << "Error during iconv conversion: " << strerror(errno) << std::endl;
        iconv_close(cd);
        return "";
    }

    // Null-terminate the output string
    *output_ptr = '\0';

    // Create the result string
    std::string result_str(output_buf.data(), output_buf.size() - output_bytes_left);

    // Close the iconv conversion descriptor
    iconv_close(cd);

    return result_str;
}

int main() {
    const char* gbk_str = "你好，世界！"; // Example GBK encoded string
    int input_len = std::strlen(gbk_str);

    std::string utf8_str = convert_gbk_to_utf8(gbk_str, input_len);
    if (!utf8_str.empty()) {
        std::cout << "UTF-8 encoded string: " << utf8_str << std::endl;
    } else {
        std::cerr << "Conversion failed." << std::endl;
    }

    return 0;
}
